package com.safeneeds.wxmana.ser.impl;

import java.io.IOException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.safeneeds.util.base.RetType;
import com.safeneeds.wxmana.dto.*;
import com.safeneeds.wxmana.entity.WxUserCache;
import com.safeneeds.wxmana.entity.WxmPublicAcc;
import com.safeneeds.wxmana.entity.WxtUser;
import com.safeneeds.wxmana.entity.dao.IWxUserCacheDao;
import com.safeneeds.wxmana.entity.dao.IWxUserDao;
import com.safeneeds.wxmana.entity.dao.IWxmPublicAccDao;
import com.safeneeds.wxmana.ser.IWxAhrService;



/**
 * 
 * @author humg
 * 2017年2月4日
 */
@Service
@Transactional
public class WxAhrService implements IWxAhrService {

	@Resource(name="wxmPublicAccDao")
	private IWxmPublicAccDao wxmPublicAccDao;
	
	@Resource(name="wxUserDao")
	private IWxUserDao wxUserDao;
	
	@Resource(name="wxUserCacheDao")
	private IWxUserCacheDao wxUserCacheDao;
	
	/**
	 * 第一步：用户同意授权，获取code
	 * @param appId 微信公众号的APPID
	 * @param url	微信回调的URL
	 * @param state	重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节 
	 * @throws IOException 
	 */	
	@Override
	public String getCode(HttpServletResponse response,HttpServletRequest request) throws IOException {
		//回调获取code
		if(request.getParameter("code")!=null){
			String code= request.getParameter("code");
			System.out.print(code);
			WxUserCache wxUserCache = wxUserCacheDao.getCodeByid(code);
			if (wxUserCache == null) {
				return getAccess_Token(code,request);
			}else {
				return wxUserCache.getCode();
			}
			
		}else {
			String redirect_uri = URLEncoder.encode(request.getRequestURL().toString(),"utf-8"); 
			String wxUrl="https://open.weixin.qq.com/connect/oauth2/authorize?";
			wxUrl=wxUrl+"appid="+WxSysInfo.Wx_Appid;
			wxUrl=wxUrl+"&redirect_uri="+redirect_uri;
			wxUrl=wxUrl+"&response_type=code";
			wxUrl=wxUrl+"&scope=snsapi_userinfo";
			wxUrl = wxUrl + "#wechat_redirect";//进行URL的拼接
			response.sendRedirect(wxUrl);
			return null;
		}
	}

	
	/**
	 * 通过code换取网页授权access_token
	 * @param appId	微信公众号的APPID
	 * @param secret 公众号的appsecret
	 * @param code 填写第一步获取的code参数
	 * @return
	 * @throws IOException 
	 */
	@Override
	public String getAccess_Token(String code,HttpServletRequest request){
		//微信接口拼接
		String url ="https://api.weixin.qq.com/sns/oauth2/access_token?";
		url=url+"appid="+WxSysInfo.Wx_Appid;
		url=url+"&secret="+WxSysInfo.Wx_Secret;
		url=url+"&code="+code;
		url=url+"&grant_type=authorization_code";
		try {
			String result=doget(url);
			//获取回调数据
			JSONObject object = JSON.parseObject(result);
			String token = object.getString("access_token");
			String expires_in = object.getString("expires_in");
			String refresh_token = object.getString("refresh_token");
			String openid = object.getString("openid");

			WxtUser user = getUserInfo(token,openid,WxSysInfo.Wx_Uuid,request);
			if(user != null){
				WxUserCache userCache = new WxUserCache();
				userCache.setCode(code);
				userCache.setWxOpenid(user.getOpenid());
				userCache.setWxPublicUuid(user.getWxPublicUuid());
				userCache.setWxUserUuid(user.getWxUid());
				wxUserCacheDao.addUserCache(userCache);
			}
			return code;
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 第三步：刷新access_token（如果需要）
	 * @param appId
	 * @param refresh_token
	 * @return
	 * @throws IOException 
	 */
	@Override
	public String UpdateAccess_Token(HttpServletResponse response,String appId, String refresh_token) throws IOException {
		String url ="https://api.weixin.qq.com/sns/oauth2/refresh_token?";
		url=url+"appid="+appId;
		url=url+"&grant_type=refresh_token";
		url=url+"&refresh_token"+refresh_token;
		response.sendRedirect(url);
		//String access_token=request.getParameter("access_token");
		return "";
	}

	/**
	 * 第四步：拉取用户信息(需scope为 snsapi_userinfo)
	 * @param access_token
	 * @param openid
	 * @return
	 * @throws IOException 
	 */
	@Override
	public WxtUser getUserInfo(String access_token, String openid,String publicUuid,HttpServletRequest request) throws IOException {
		String url = "https://api.weixin.qq.com/sns/userinfo?";
		url = url+"&access_token="+access_token;
		url = url+"&openid="+openid;
		url = url+"&lang=zh_CN";
		String result = doget(url);
		result = new String(result.getBytes("ISO-8859-1"),"UTF-8");
		JSONObject object = JSON.parseObject(result);
		WxtUser user = new WxtUser();
		//保存用户基本数据
		user.setNickname(object.getString("nickname"));
		user.setSex(object.getString("sex"));
		user.setProvince(object.getString("province"));
 		user.setCity(object.getString("city"));
 		user.setCountry(object.getString("country"));
 		user.setHeadimgurl(object.getString("headimgurl"));
 		user.setUnionid(object.getString("unionid"));
 		user.setOpenid(openid);
 		user.setWxPublicUuid(publicUuid);
 		WxtUser wxtUser = new WxtUser();
 		wxtUser = wxUserDao.getUserByOpenidAndUuid(openid, publicUuid);
 		if(wxtUser != null){
 			user.setWxUid(wxtUser.getWxUid());
 		}
 		
 		//该用户不存在的话，插入数据
 		if(wxtUser == null && user.getNickname() != null){
 			user = wxUserDao.addWxUser(user);
 		}
 		
 		return user;
	}

	/**
	 * 附：检验授权凭证（access_token）是否有效
	 * @param access_token
	 * @param openid
	 * @return
	 * @throws IOException 
	 */
	@Override
	public String checkAccess_Token(HttpServletResponse response,String access_token, String openid) throws IOException {

		String url="https://api.weixin.qq.com/sns/auth?";
		url=url+"&access_token="+access_token;
		url=url+"&openid="+openid;
		response.sendRedirect(url);
		//String errcode=request.getParameter("errcode");
		return "";
	}


	/**
	 * 
	 * @param url
	 * @return GET向服务器发送请求
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@Override
	public String doget(String url) throws ClientProtocolException, IOException {
		 String body = "{}";
	        DefaultHttpClient httpclient = new DefaultHttpClient();
	        try {
	            HttpGet httpget = new HttpGet(url);
	            HttpResponse response = httpclient.execute(httpget);
	            HttpEntity entity = response.getEntity();
	            body = EntityUtils.toString(entity);
	        } finally {
	            httpclient.getConnectionManager().shutdown();
	        }
	        return body;
	}


	/**
	 * 根据openid，uuid获取微信用户
	 * @param openid
	 * @param uuid
	 * @return
	 */
	@Override
	public WxtUser getUserByOpenidAndUuid(String openid, String uuid) {
		return wxUserDao.getUserByOpenidAndUuid(openid, uuid);
	}


	/**
	 * 根据用户id获取缓存信息
	 * @param code
	 * @return
	 */
	@Override
	public WxUserCache getUserCacheByid(String code) {
		return wxUserCacheDao.getCodeByid(code);
	}

	/**
	 * 根据用户id获取用户信息
	 * @param wxuid
	 * @return
	 */
	@Override
	public WxtUser getUserByid(String wxuid) {
		return wxUserDao.getWxUserById(wxuid);
	}


	/**
	 * 根据微信Uid获取用户缓存信息
	 * @param wxuid
	 * @return
	 */
	@Override
	public WxUserCache getUserCacheByUid(String wxuid) {
		return wxUserCacheDao.getUserCacheByUid(wxuid);
	}


	/**
	 * 根据微信公共Uid获取公众号信息
	 * @param wxPublicUuid
	 * @return
	 */
	@Override
	public WxmPublicAcc getPublicAccByWxPubUid(String wxPublicUuid) {
		return wxmPublicAccDao.getWxmPublicAccById(wxPublicUuid);
	}


	/**
	 * 删除缓存信息
	 * @param userCache
	 */
	@Override
	public void delUserCache(WxUserCache userCache) {
		wxUserCacheDao.delUserCache(userCache);
	}


	



	
	
	
	

}
